thin.define(function(exports) {
	var self = this;

	/* 
	 * 开始投注
	 * 根据最新注单和金额判断是否投注成功
	 */
	function main(data_opt, complete) {
		// var playId = data_opt['betBean[0].playId'];

		var queue = new self.Queue();

		// 开始投注
		queue.add(function(nextStep) {
			// submitBet(data_opt, nextStep);
			submitBet(data_opt, function(res) {
				if (res.data && res.data.code == 400) {
					// 已封盘
					complete(false, res.data.msg);
					queue.abort();
				} else {
					nextStep();
				}
			});
		});

		// 投注成功后延迟2秒检测结果
		/* queue.add(function(nextStep) {
			setTimeout(nextStep, 2.4 * 1000);
		}); */

		// 获取投注结果
		queue.add(function(nextStep) {
			requestLottery(function(data) {
				/* if (data.userBetNew && data.userBetNew.length) {
					// 有投注信息
					var judge = detection(data.userBetNew, playId);
					if (judge) {
						// 相同的playId
						thin.store_opts.playId = playId;
						complete(true);
					} else {
						// 不同的playId
						setTimeout(function() {
							main(data_opt, complete);
						}, 4 * 1000);
					}
				} else {
					// 无投注信息
					setTimeout(function() {
						main(data_opt, complete);
					}, 4 * 1000);
				} */
				// 有投注信息
				var judge = detection(data.userBetNew);
				if (judge) {
					// 相同的playId
					// thin.store_opts.playId = playId;
					complete(true);
				} else {
					// 不同的playId
					setTimeout(function() {
						main(data_opt, complete);
					}, 4 * 1000);
				}
			});
			nextStep();
		});

		queue.run();
	}

	// ---------------------------------------------

	// 开始投注
	function submitBet(data_opt, complete) {
		var url = thin.extData.origin + '/bet/bet.do?_t=' + Date.now();
		thin.ajax.post(url, data_opt, complete);
	}

	// 获取投注信息
	function requestLottery(complete) {
		var url = thin.extData.origin + '/game/getLotteryData.do';
		var data_opt = {
			// '_t': Date.now(),
			'gameId': thin.store_bets.gameId
		};
		var again = 5;
		request();

		function request() {
			data_opt['_t'] = Date.now();
			thin.ajax.get(url, data_opt, function(res) {
				// console.dir(res);
				if (res.state) {
					// 防止下注后订单未及时响应导致读取空数据
					if (res.data.userBetNew && res.data.userBetNew.length) {
						complete(res.data);
					} else {
						if (again > 0) {
							setTimeout(request, 1.6 * 1000);
							--again;
						} else {
							complete();
						}
					}
				} else {
					if (again > 0) {
						setTimeout(request, 1.6 * 1000);
						--again;
					} else {
						complete();
					}
				}
			});
		}
	}

	// 检测有无对应的playId的注单
	function detection(data) {
		var playId_arr = thin.store_opts.playId_arr;
		var judge = false;
		for (var i in data) {
			var item = data[i];
			if (playId_arr.indexOf(Number(item.playId)) != -1) {
				judge = true;
				break;
			}
		}
		return judge;
	}

	exports('submitBet', main);
});
